import crypto from 'crypto';

import FingerprintJS from '@fingerprintjs/fingerprintjs';
import { useMutation } from '@tanstack/react-query';
import { App } from 'antd';
import { useNavigate } from 'react-router-dom';
import { create } from 'zustand';

import { USER_LIST, PERMISSION_LIST } from '@/_mock/assets';
import sharelink from '@/api/services/sharelink';
import userService, { SignInReq } from '@/api/services/userService';
import { UserInfo, UserToken } from '@/types/entity'; //
import { StorageEnum } from '@/types/enum';
import { TeamMemberItemType } from '@/types/user/team/type';
import { getItem, removeItem, setItem } from '@/utils/storage';

import { useTourActions } from './tourStore';

const { VITE_TOKEN: VITETOKEN } = import.meta.env;

export const hashStr = (str: string) => {
  return crypto.createHash('sha256').update(str).digest('hex');
};

const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env;

type UserStore = {
  userInfo: Partial<UserInfo>;
  userToken: UserToken;
  isGuest: boolean;
  isAdmin: boolean;
  teamMembers: TeamMemberItemType[];
  // 使用 actions 命名空间来存放所有的 action
  actions: {
    setUserInfo: (userInfo: UserInfo) => void;
    setUserToken: (token: UserToken) => void;
    clearUserInfoAndToken: () => void;
    clearUserInfo: () => void;
    loadAndGetTeamMembers: (init?: boolean) => Promise<TeamMemberItemType[]>;
    updateUserDetailInfo: (detailInfo: Partial<UserInfo>) => void;
    initUserDetailInfo: (id?: string) => Promise<void>;
  };
};

const useUserStore = create<UserStore>((set, get) => {
  const userInfo = getItem<UserInfo>(StorageEnum.User) || {
    role: undefined,
  };
  const userToken = getItem<UserToken>(StorageEnum.Token) || {};

  return {
    userInfo,
    userToken,
    isGuest: userInfo?.role?.code === 'guest' || userInfo?.role?.code?.includes('guest') || false,
    isAdmin: userInfo?.role?.code === 'admin' || userInfo?.role?.code?.includes('admin') || false,
    teamMembers: [],
    actions: {
      setUserInfo: (userInfo) => {
        const isGuest =
          userInfo?.role?.code === 'guest' || userInfo?.role?.code?.includes('guest') || false;
        const isAdmin =
          userInfo?.role?.code === 'admin' || userInfo?.role?.code?.includes('admin') || false;
        set({ userInfo, isGuest, isAdmin });
        setItem(StorageEnum.User, userInfo);
      },
      setUserToken: (userToken) => {
        set({ userToken });
        setItem(StorageEnum.Token, userToken);
      },
      clearUserInfoAndToken() {
        set({ userInfo: {}, userToken: {} });
        removeItem(StorageEnum.User);
        removeItem(StorageEnum.Token);
      },
      clearUserInfo() {
        set({ userInfo: {} });
        removeItem(StorageEnum.User);
      },
      loadAndGetTeamMembers: async (init = false) => {
        if (false) return [];

        const randomRefresh = Math.random() > 0.7;
        if (!randomRefresh && !init && get().teamMembers?.length)
          return Promise.resolve(get().teamMembers);

        const res = await userService.getTeamMembers();
        set({ teamMembers: res });

        return res;
      },
      updateUserDetailInfo: (detailInfo) => {
        set((state) => {
          const updatedUserInfo = { ...state.userInfo, ...detailInfo };
          setItem(StorageEnum.User, updatedUserInfo);
          return { userInfo: updatedUserInfo };
        });
      },
      initUserDetailInfo: async (id?: string) => {
        try {
          if (!id) {
            console.warn('initUserDetailInfo: No user ID provided');
            return;
          }

          const response = await userService.getUserInfo(id);
          const userDetail = Array.isArray(response) ? response[0] : response;

          if (userDetail) {
            // 更新用户详细信息到store
            set((state) => {
              const updatedUserInfo = {
                ...state.userInfo,
                avatar: userDetail.avatar,
              };
              setItem(StorageEnum.User, updatedUserInfo);
              return { userInfo: updatedUserInfo };
            });
          }
        } catch (error) {
          console.error('Failed to fetch user detail info:', error);
        }
      },
    },
  };
});

export const useUserInfo = () => useUserStore((state) => state.userInfo);
export const useUserState = () => useUserStore((state) => state);
export const useUserToken = () => useUserStore((state) => state.userToken);
export const useUserPermission = () =>
  useUserStore((state) => {
    // return state.userInfo.permissions
    return PERMISSION_LIST;
  });
export const useUserActions = () => useUserStore((state) => state.actions);

export const useSignIn = () => {
  const navigatge = useNavigate();
  const { message } = App.useApp();
  const { setUserToken, setUserInfo, initUserDetailInfo } = useUserActions();
  const { setIsFirstLogin } = useTourActions();

  const signInMutation = useMutation({
    mutationFn: userService.signin,
  });

  const signIn = async (data: SignInReq) => {
    try {
      data.password = hashStr(data.password);
      const res = await signInMutation.mutateAsync(data);
      const { user, token } = res;

      // 新增逻辑：根据登录返回的 isTianGong 字段，设置本地缓存
      // const isTianGong = user?.is_TianGong === 'true' || user?.is_TianGong === true;
      // if (isTianGong) {
      //   setItem(StorageEnum.TiangongManagerRoles, true);
      // } else {
      //   // 确保非天工角色登录时，清除旧的缓存标记
      //   removeItem(StorageEnum.TiangongManagerRoles);
      // }
      // 使用 user.is_TianGong 字段，不再写 TiangongManagerRoles 本地缓存

      const isFirstLogin = res?.is_first_login;
      // setIsFirstLogin(isFirstLogin || false)

      const fakerUser = USER_LIST[0];
      const mergeUser = { ...fakerUser, ...user, isFirstLogin };

      setUserToken({ accessToken: token, refreshToken: token });
      setUserInfo(mergeUser);

      initUserDetailInfo(user?._id).catch((error) => {
        console.error('Failed to init user detail info:', error);
      });

      navigatge(HOMEPAGE, { replace: true });
    } catch (err) {
      // message.warning({
      //   content: err.message,
      //   duration: 3,
      // });
    }
  };

  return signIn;
};

// 访客登录
export const useAnonymousSignIn = () => {
  const navigatge = useNavigate();
  const { message } = App.useApp();
  const { setUserToken, setUserInfo } = useUserActions();

  const signInMutation = useMutation({
    mutationFn: sharelink.anonymousLogin, // 确保这里引用的是修正后的函数
  });

  const signIn = async (share_code: string) => {
    try {
      const fp = await FingerprintJS.load();
      const { visitorId } = await fp.get();

      const payload = { share_code, device_code: visitorId };

      const res = await signInMutation.mutateAsync(payload);
      console.log(res);

      // const { user, token } = res;

      // const fakerUser = USER_LIST[0];
      // const mergeUser = { ...fakerUser, ...user, avatar: fakerUser.avatar };

      // setUserToken({ accessToken:token, refreshToken:token });
      // setUserInfo(mergeUser);
      // navigatge(HOMEPAGE, { replace: true });
      return res;
    } catch (err) {
      message.warning({
        content: err.message,
        duration: 3,
      });
    }
  };

  return signIn;
};
export default useUserStore;
